package com.msb;

/**
 * @author whf
 * @date 2024-12-17 11:13
 */

// 测试链接：https://leetcode.com/problems/merge-two-sorted-lists
public class _12_easy合并两个有序链表 {

    // 不要提交这个类
    public static class ListNode {
        public int val;
        public ListNode next;
    }

    // 先判断开头, 哪个小取哪个
    // 两个链表同时遍历, 小的往后接
    // 最后肯定有个链表先消耗光, 没消耗完的接在后面
    public static ListNode mergeTwoLists(ListNode head1, ListNode head2) {
        if (head1 == null || head2 == null) {
            return head1 == null ? head2 : head1;
        }
        ListNode start = head1.val < head2.val ? head1 : head2;
        ListNode other = start == head1 ? head2 : head1;
        ListNode startPre = start;
        ListNode cur = start.next;
        while (cur != null && other != null) {
            if (cur.val > other.val) {
                startPre.next = other;
                other = other.next;
            } else {
                startPre.next = cur;
                cur = cur.next;
            }
            startPre = startPre.next;
        }
        startPre.next = cur == null ? other : cur;
        return start;
    }

}
